package com.lsfb.signln.Statistics.EvectionSearch;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.lsfb.signln.R;
import com.lsfb.signln.Statistics.EvectionSearch.SearchResult.PreviewPdf.PreviewPdfActivity;
import com.lsfb.signln.Statistics.EvectionSearch.SearchResult.SearchResultActivity;
import com.lsfb.signln.Statistics.codescan.MipcaActivityCapture;
import com.lsfb.signln.Utils.HttpDownloader;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.LsfbTimePicker;
import com.lsfb.signln.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 出差查询
 * Created by Administrator on 2018/1/31 0031.
 */
@ContentView(R.layout.aty_evection_search)
public class EvectionSearchActivity extends LsfbActivity {

    /**
     * 差旅单号
     */
    @ViewInject(R.id.aty_search_et_import)
    private EditText et_import;

    /**
     * 开始时间
     */
    @ViewInject(R.id.aty_search_text_start_time)
    private TextView text_start_time;

    /**
     * 结束时间
     */
    @ViewInject(R.id.aty_search_text_end_time)
    private TextView text_end_time;

    private DatePickerDialog datePickerDialog;

    /**
     * 日期选择器变量
     */
    private Calendar start_showDate;

    //timePicker
    private LsfbTimePicker starttime, endtime;
    //开始时间
    private String start_time = "";
    //结束时间
    private String end_time = "";

    private Handler handler=new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what){
                case 1000:
                    et_import.setText("");
                    LittleUtils.code_resultString="";
                    break;
            }
        }
    };

    @Override
    public void initView() {

        //开始时间
        starttime = new LsfbTimePicker(this);
        starttime.SelectSureListenner(new LsfbTimePicker.ClickSureListener() {
            @Override
            public void ClickSure(String time) {
                if (!end_time.isEmpty()) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date start_date = df.parse(time);
                        Date end_date = df.parse(end_time);
                        if (end_date.getTime() < start_date.getTime()) {
                            //结束时间小于开始时间
                            T.showShort(getApplicationContext(), "开始时间不能大于结束时间");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                start_time = time;
                text_start_time.setText(time);
            }
        });

        //结束时间
        endtime = new LsfbTimePicker(this);
        endtime.SelectSureListenner(new LsfbTimePicker.ClickSureListener() {
            @Override
            public void ClickSure(String time) {
                if (!start_time.isEmpty()) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date start_date = df.parse(start_time);
                        Date end_date = df.parse(time);
                        if (end_date.getTime() < start_date.getTime()) {
                            //结束时间小于开始时间
                            T.showShort(getApplicationContext(), "结束时间不能小于开始时间");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                end_time = time;
                text_end_time.setText(time);
            }
        });
    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_back, R.id.aty_code, R.id.aty_search_img, R.id.aty_search_start_time, R.id.aty_search_end_time, R.id.aty_search_go})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.aty_back:
                finish();
                break;
            //二维码
            case R.id.aty_code:
                startActivity(new Intent(this, MipcaActivityCapture.class));
                break;
            //搜索
            case R.id.aty_search_img:
                if (!et_import.getText().toString().isEmpty()){
                    new downloadPDFThread().start();
                }else {
                    T.showShort(this,"请输入差旅单号");
                }
                break;
            //开始时间
            case R.id.aty_search_start_time:
//                //日期选择器
//                datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//                        start_showDate.set(Calendar.YEAR, year);
//                        start_showDate.set(Calendar.MONTH, monthOfYear);
//                        start_showDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
//                        text_start_time.setText((String) DateFormat.format("yyyy-MM-dd", start_showDate));
//
//                    }
//                }, start_showDate.get(Calendar.YEAR), start_showDate.get(Calendar.MONTH), start_showDate.get(Calendar.DAY_OF_MONTH));
//                datePickerDialog.show();
                starttime.showTimePickerView();
                break;
            //结束时间
            case R.id.aty_search_end_time:
//                //日期选择器
//                datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
//                    @Override
//                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//                        start_showDate.set(Calendar.YEAR, year);
//                        start_showDate.set(Calendar.MONTH, monthOfYear);
//                        start_showDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
//                        text_end_time.setText((String) DateFormat.format("yyyy-MM-dd", start_showDate));
//
//                    }
//                }, start_showDate.get(Calendar.YEAR), start_showDate.get(Calendar.MONTH), start_showDate.get(Calendar.DAY_OF_MONTH));
//                datePickerDialog.show();
                endtime.showTimePickerView();
                break;
            //查看差率清单
            case R.id.aty_search_go:
                if (!text_start_time.getText().toString().isEmpty() && !text_end_time.getText().toString().isEmpty()){
                    startActivity(new Intent(this, SearchResultActivity.class)
                            .putExtra("start_time", text_start_time.getText().toString())
                            .putExtra("end_time", text_end_time.getText().toString()));
                }else {
                    T.showShort(this,"请选择开始及结束时间");
                }
                break;
        }
    }

    @Override
    public void initData() {

    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        et_import.setText(LittleUtils.code_resultString);
        if (!et_import.getText().toString().isEmpty()){
            new downloadPDFThread().start();
        }
    }


    class downloadPDFThread extends Thread {
        public void run() {
            HttpDownloader httpDownloader = new HttpDownloader();
            int downloadResult = httpDownloader.downloadFiles(
                    URLString.DOWNBYNUM + "?number=" + et_import.getText().toString(),
                    "sign", "个人出差统计.pdf");
            LsfbLog.e("下载结果：" + downloadResult);


            switch (downloadResult) {
                case -1:        //下载失败
                    T.showShort(getApplicationContext(), "下载PDF失败");
                    break;
                case 0:
                case 1:
                    String downloadUrl = URLString.DOWNBYNUM + "?number=" + LittleUtils.xiazai;
                    handler.sendEmptyMessage(1000);
                    startActivity(new Intent(EvectionSearchActivity.this, PreviewPdfActivity.class)
                            .putExtra("downloadUrl", downloadUrl));
                    break;
            }
        }
    }
}
